﻿<%@ Page Language="C#" MasterPageFile="../../main.master" Inherits="VioletDevelopmentLaboratory.Net.Web.PageBase" %>

<%@ Register src="modify.ascx" tagname="modify" tagprefix="uc1" %>

<script runat="server">
	private Board currentBoard;
	
	protected void Page_Load(object sender, EventArgs e)
	{
		if (Request.UrlReferrer == null)
		{
			Response.Redirect("list.aspx");
		}

		currentBoard = Board.GetBoard(Request.QueryString["id"]);
		
		if (!Page.IsPostBack)
		{
			CategorysGridView_DataBind();
		}
	}

	protected void MoveButton_Click(object sender, EventArgs e)
	{
		if (!String.IsNullOrEmpty(CategoryDropDownList.SelectedValue) && !String.IsNullOrEmpty(BoardDropDownList.SelectedValue))
		{
			switch (BoardCategory.Move(currentBoard.ComponentID, CategoryDropDownList.SelectedValue, BoardDropDownList.SelectedValue))
			{
				case BoardCategoryMoveResult.Success :
					VUtility.ShowAlert(Page, "카테고리가 이동되었습니다.");
					CategorysGridView_DataBind();
					break;
				case BoardCategoryMoveResult.InvalidSourceCategory :
					VUtility.ShowAlert(Page, "원본 카테고리를 알 수 없습니다.");
					break;
				case BoardCategoryMoveResult.InvalidDestBoard :
					VUtility.ShowAlert(Page, "대상 게시판을 알 수 없습니다.");
					break;
				case BoardCategoryMoveResult.ExistsDestCategory :
					VUtility.ShowAlert(Page, "대상 게시판에 같은 카테고리가 존재합니다.");
					break;
			}
		}
		else
		{
			VUtility.ShowAlert(Page, "원본 카테고리 또는 대상 게시판이 선택되지 않았습니다.");
		}
	}

	protected void AddButton_Click(object sender, EventArgs e)
	{
		if (Page.IsValid)
		{
			BoardCategoryCreateResult createResult;
			
			if (CategoryIconFileUpload.HasFile)
			{
				if (CategoryIconFileUpload.PostedFile.ContentLength > 102400)
				{
					VUtility.ShowMessagePanel(Page, "Icon파일 용량이 너무 큽니다.", true);
					return;
				}

				createResult = BoardCategory.Create(currentBoard.ComponentID, CategoryNameTextBox.Text, CategorysGridView.Rows.Count, CategoryIconFileUpload.PostedFile);
			}
			else
			{
				createResult = BoardCategory.Create(currentBoard.ComponentID, CategoryNameTextBox.Text, CategorysGridView.Rows.Count);
			}

			switch (createResult)
			{
				case BoardCategoryCreateResult.Success :
					VUtility.ShowAlert(Page, "카테고리를 만들었습니다.");
					CategorysGridView_DataBind();
					CategoryNameTextBox.Text = "";
					break;
				case BoardCategoryCreateResult.Exists :
					VUtility.ShowAlert(Page, "카테고리가 존재합니다.");
					break;
			}
		}
	}

	protected void CategorysGridView_DataBind()
	{
		CategorysGridView.DataSource = currentBoard.GetCategoryCollection();
		CategorysGridView.DataBind();

		CategoryDropDownList.DataSource = CategorysGridView.DataSource;
		CategoryDropDownList.DataBind();
	}
	protected void CategorysGridView_RowCommand(object sender, GridViewCommandEventArgs e)
	{
		if (e.CommandName == "RemoveIcon")
		{
			switch (BoardCategory.RemoveIcon(currentBoard.ComponentID, e.CommandArgument.ToString()))
			{
				case BoardCategoryDeleteIconResult.Success :
					VUtility.ShowAlert(Page, "카테고리 아이콘을 삭제했습니다.");
					CategorysGridView_DataBind();
					break;
				case BoardCategoryDeleteIconResult.EmptyIcon :
					VUtility.ShowAlert(Page, "삭제할 아이콘이 없습니다.");
					break;
				case BoardCategoryDeleteIconResult.InvalidCategory:
					VUtility.ShowAlert(Page, "알 수 없는 카테고리입니다.");
					break;
			}
		}
	}
	protected void CategorysGridView_RowEditing(object sender, GridViewEditEventArgs e)
	{
		CategorysGridView.EditIndex = e.NewEditIndex;
		CategorysGridView_DataBind();
	}
	protected void CategorysGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
	{
		CategorysGridView.EditIndex = -1;
		CategorysGridView_DataBind();
	}
	protected void CategorysGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
	{
		FileUpload CategoryIconFileUpload = (FileUpload)CategorysGridView.Rows[e.RowIndex].FindControl("CategoryIconFileUpload");
		TextBox NameTextBox = (TextBox)CategorysGridView.Rows[e.RowIndex].FindControl("NameTextBox");
		TextBox IndexTextBox = (TextBox)CategorysGridView.Rows[e.RowIndex].FindControl("IndexTextBox");
		
		BoardCategoryUpdateResult updateResult;
		
		if (CategoryIconFileUpload.HasFile)
		{
			if (CategoryIconFileUpload.PostedFile.ContentLength > 102400)
			{
				VUtility.ShowMessagePanel(Page, "Icon파일 용량이 너무 큽니다.", true);
				e.Cancel = true;
				return;
			}

			updateResult = BoardCategory.Modify(currentBoard.ComponentID, CategorysGridView.DataKeys[e.RowIndex].Value.ToString(), NameTextBox.Text, Int32.Parse(IndexTextBox.Text), CategoryIconFileUpload.PostedFile);				
		}
		else
		{
			updateResult = BoardCategory.Modify(currentBoard.ComponentID, CategorysGridView.DataKeys[e.RowIndex].Value.ToString(), NameTextBox.Text, Int32.Parse(IndexTextBox.Text));
		}

		switch (updateResult)
		{
			case BoardCategoryUpdateResult.Success :
				VUtility.ShowAlert(Page, "카테고리를 업데이트했습니다.");
				CategorysGridView.EditIndex = -1;
				CategorysGridView_DataBind();
				break;
			case BoardCategoryUpdateResult.InvalidCategory:
				VUtility.ShowAlert(Page, "알 수 없는 카테고리입니다.");
				break;
		}
	}
	protected void CategorysGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
	{
		switch (BoardCategory.Remove(currentBoard.ComponentID, CategorysGridView.DataKeys[e.RowIndex].Value.ToString()))
		{
			case BoardCategoryDeleteResult.Success :
				VUtility.ShowAlert(Page, "카테고리를 삭제했습니다.");
				CategorysGridView.EditIndex = -1;
				CategorysGridView_DataBind();
				break;
			case BoardCategoryDeleteResult.InvalidCategory:
				VUtility.ShowAlert(Page, "알 수 없는 카테고리입니다.");
				break;
		}
	}
</script>

<asp:Content ID="Content1" ContentPlaceHolderID="BodyContentPlaceHolder" runat="server">
	<asp:ObjectDataSource ID="BoardDropDownListDataSource" runat="server" 
		SelectMethod="GetBoardCollection" 
		TypeName="VioletDevelopmentLaboratory.Net.Web.Component.Board">
	</asp:ObjectDataSource>
	
	<h2>게시판 &gt; 목록 &gt; <%= String.Format("{0} ({1})", currentBoard.ComponentID, currentBoard.Name) %> &gt; 카테고리</h2>

	<uc1:modify ID="modify1" runat="server" />

	<fieldset>
		<legend>카테고리 이동</legend>
		<asp:DropDownList ID="CategoryDropDownList" runat="server" DataTextField="Name" DataValueField="CategoryID" />을(를)
		<asp:DropDownList ID="BoardDropDownList" runat="server" 
						DataSourceID="BoardDropDownListDataSource" DataTextField="ComponentId"
			DataValueField="ComponentId" />게시판으로
		<asp:Button ID="MoveButton" runat="server" OnClick="MoveButton_Click" Text="이동" 
						CausesValidation="False" />
		<span style="color : #ff0000;">※ 주의 : 카테고리 이동시 포함된 글도 함께 이동됩니다.</span>
	</fieldset>
		
	<fieldset>
		<legend>카테고리 관리</legend>
		<table cellspacing="0" cellpadding="5" rules="all" border="1" style="border-collapse : collapse;">
			<tr>
				<td>Name</td>
				<td>
					<asp:TextBox ID="CategoryNameTextBox" runat="Server" ValidationGroup="Add" />
					<asp:RequiredFieldValidator ID="CategoryNameTextBoxRequiredFieldValidator" 
						runat="server" ControlToValidate="CategoryNameTextBox" Display="Dynamic" 
						ErrorMessage="*" ValidationGroup="Add" />
				</td>
			</tr>
			<tr>
				<td>Icon</td>
				<td>
					<asp:FileUpload ID="CategoryIconFileUpload" runat="server" /> (jpg, gif, png, 100KB)
				</td>
			</tr>
			<tr>
				<td colspan="2">
					<asp:Button ID="AddButton" runat="Server" Text="추가" 
						OnClick="AddButton_Click" ValidationGroup="Add" />
				</td>
			</tr>
		</table>

		<asp:GridView ID="CategorysGridView" runat="server" AutoGenerateColumns="False" 
			DataKeyNames="CategoryId" 
			Width="100%" PageSize="20" EmptyDataText="카테고리가 없습니다." onrowcommand="CategorysGridView_RowCommand" 
			onrowupdating="CategorysGridView_RowUpdating" 
			onrowediting="CategorysGridView_RowEditing" 
			onrowcancelingedit="CategorysGridView_RowCancelingEdit" 
			onrowdeleting="CategorysGridView_RowDeleting">
			<Columns>
				<asp:CommandField ButtonType="Button" ShowEditButton="True" UpdateText="변경" >
					<ItemStyle HorizontalAlign="Center" />
				</asp:CommandField>
				<asp:BoundField DataField="CategoryID" ReadOnly="true" HeaderText="ID" />
				<asp:TemplateField HeaderText="Icon">
					<ItemTemplate>
						<img src='<%# Eval("IconImageUrl") %>' alt="" />
					</ItemTemplate>
					<EditItemTemplate>
						<asp:FileUpload ID="CategoryIconFileUpload" runat="server" />
					</EditItemTemplate>
					<ItemStyle HorizontalAlign="Center" />
				</asp:TemplateField>
				<asp:TemplateField HeaderText="Name">
					<ItemTemplate>
						<%# Eval("Name") %>
					</ItemTemplate>
					<EditItemTemplate>
						<asp:TextBox ID="NameTextBox" runat="server" Text='<%# Bind("Name") %>' />
						<asp:RequiredFieldValidator ID="NameTextBoxRequiredFieldValidator" 
							runat="server" ErrorMessage="*" ControlToValidate="NameTextBox" 
							Display="Dynamic"></asp:RequiredFieldValidator>
					</EditItemTemplate>
				</asp:TemplateField>
				<asp:TemplateField HeaderText="Index">
					<ItemTemplate>
						<%# Eval("Index") %>
					</ItemTemplate>
					<EditItemTemplate>
						<asp:TextBox ID="IndexTextBox" runat="server" Text='<%# Bind("Index") %>' />
						<asp:RequiredFieldValidator ID="IndexTextBoxRequiredFieldValidator" 
							runat="server" ErrorMessage="*" ControlToValidate="IndexTextBox" 
							Display="Dynamic"></asp:RequiredFieldValidator>
						<asp:CompareValidator ID="IndexTextBoxCompareValidator" runat="server" 
							ErrorMessage="*" ControlToValidate="IndexTextBox" Display="Dynamic" 
							Operator="DataTypeCheck" Type="Integer"></asp:CompareValidator>
					</EditItemTemplate>
					<ItemStyle HorizontalAlign="Center" />
				</asp:TemplateField>
				<asp:BoundField DataField="ThreadCount" HeaderText="ThreadCount" 
					ReadOnly="true" >
					<ItemStyle HorizontalAlign="Center" />
				</asp:BoundField>
				<asp:TemplateField>
					<ItemTemplate>
						<asp:Button ID="RemoveIconButton" runat="server" Text="Icon 제거" CommandName="RemoveIcon" CommandArgument='<%# Eval("CategoryID") %>' CausesValidation="false" OnClientClick="<%$ Resources:VGlobalResources, General_Script_RemoveConfirm %>" />
						<asp:Button ID="DeleteButton" runat="server" Text="제거" CommandName="Delete" OnClientClick="<%$ Resources:VGlobalResources, General_Script_RemoveConfirm %>" />
					</ItemTemplate>
					<ItemStyle HorizontalAlign="Center" />
				</asp:TemplateField>
			</Columns>
		</asp:GridView>
	</fieldset>

</asp:Content>